var express = require('express');
const fine = express.Router();
var bodyParser = require('body-parser');
const path = require("path");
const Database = require("better-sqlite3");
//获取数据库中管理员账号密码等信息
const mydb = new Database(path.resolve(__dirname, "../database/infor.db"), { verbose: console.log });

// 创建 application/x-www-form-urlencoded 编码解析
fine.use(bodyParser.urlencoded({ extended: false }))
fine.use(express.json());
fine.use(bodyParser.json());

fine.post('/stufine', function (req, res) {
    // 获取前端数据
    var response = {
        "stu_id": req.body.stu_id
    };
    // console.log(response);
    //指定数据库文件路径
    const get_user_by_id = mydb.prepare('SELECT * FROM fine WHERE stuid= ?');//一个查询语句对象
    var a = get_user_by_id.get(response.stu_id);//执行查询
    // console.log(a);
    if (a) {
        if (a.state == "no") {
            const updata_fine = mydb.prepare('UPDATE fine SET state =@state  WHERE stuid=@stuid');
            updata_fine.run({ state: "yes", stuid: response.stu_id });
            res.sendFile(path.resolve(__dirname, "../public/html/fine_success.html"));
        }
        else{
            // 没有罚款
            console.log("无罚款");
            res.sendFile(path.resolve(__dirname, "../public/html/fine_error1.html"));
        }
    }
    else {
        // 如果没有查询到，说明该同学不存在
        console.log("该同学不存在");
        res.sendFile(path.resolve(__dirname, "../public/html/fine_error2.html"));
    }
});

module.exports = fine;